import React, { Component } from 'react'
import { Card, Button, Table, Modal, Input, Form, message, Tree } from 'antd'
import { reqRoles, reqRoleAdd, reqRoleUpdate } from '../../api'
import menuList from '../../config/menuConfig'

import { PAGE_SIZE } from '../../utils/constants'

export default class Role extends Component {
  state = {
    roles: [], // 所有角色的列表
    role: {}, // 选中的role
    isShowAdd: false, // 是否显示添加界面
    isShowAuth: false, // 是否显示设置界面
    roleName: '',
    checkedKeys: []
  }

  initColumn = () => {
    this.columns = [
      {
        title: '角色名称',
        dataIndex: 'name'
      }, {
        title: '创建时间',
        dataIndex: 'create_time'
      }, {
        title: '授权时间',
        dataIndex: 'auth_time'
      }, {
        title: '授权人',
        dataIndex: 'auth_name'
      }
    ]
  }

  onRow = (role) => {
    return {
      onClick: event => { // 点击行
        const checkedKeys = role.menus
        this.setState({ role, checkedKeys })
        console.log(role);
      }
    }
  }

  getRoles = async () => {
    const { data: result } = await reqRoles()
    if (result.status === 0) {
      const roles = result.data
      this.setState({ roles })
    }
  }

  // 添加角色
  validateRole = () => {
    this.formRef.current.validateFields()
      .then(values => {
        this.addRole(values)
        this.formRef.current.validateFields()
      })
      .catch(info => {
        let error = info.errorFields
        console.log(error);
        error.forEach(item => {
          message.error(item.errors)
        })
      });

  }

  addRole = async (values) => {
    const { data: result } = await reqRoleAdd(values.roleName)
    this.setState({ isShowAdd: false })
    if (result.status === 0) {
      message.success('添加角色成功')
    } else {
      message.error('添加角色失败')
    }
    this.getRoles()
  }

  updateRole = async () => {
    const role = this.state.role
    // 得到最新的menu
    const menus = this.state.checkedKeys
    role.menus = menus
    const { data: result } = await reqRoleUpdate(role)

    if(result.status === 0) {
      message.success('设置角色权限成功')
      this.setState({
        roles: [...this.state.roles]
      })
    } else {
      message.error(result.msg)
    }
  }

  onCheck = checkedKeys => {
    this.setState({ checkedKeys })
  }

  componentWillMount() {
    this.initColumn()
  }

  componentDidMount() {
    this.getRoles()
  }

  formRef = React.createRef();

  render() {
    const { roles, role, isShowAdd, isShowAuth, checkedKeys } = this.state

    const treeData = [{
      title: '平台权限',
      key: 'all',
      children: [...menuList]
    }]

    const title = (
      <span>
        <Button type="primary" onClick={() => this.setState({ isShowAdd: true })}>创建角色</Button>
        <Button type="primary" onClick={() => this.setState({ isShowAuth: true })} disabled={!role._id} style={{ marginLeft: 15 }}>设置角色权限</Button>
      </span>
    )

    return (
      <Card title={title}>
        <Table
          bordered
          rowKey="_id"
          dataSource={roles}
          columns={this.columns}
          pagination={{ defaultPageSize: PAGE_SIZE }}
          rowSelection={{ type: 'radio', selectedRowKeys: [role._id] }}
          onRow={this.onRow}
        />
        <Modal title="添加角色" visible={isShowAdd === true} onOk={this.validateRole} onCancel={() => { this.setState({ isShowAdd: false }) }}>
          <Form ref={this.formRef}>
            <Form.Item
              label="角色名称"
              name="roleName"
              rules={[{ required: true, whitespace: true, message: '角色名称必须输入' }]}
            >
              <Input></Input>
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="设置角色权限" visible={isShowAuth === true} onOk={this.updateRole} onCancel={() => { this.setState({ isShowAuth: false }) }}>
          <Form>
            <Form.Item
              label="角色名称"
              name="roleName"
              rules={[{ required: true, whitespace: true, message: '角色名称必须输入' }]}
            >
              <Input disabled key={role._id} defaultValue={role.name}></Input>
            </Form.Item>
            <Tree
              checkable
              defaultExpandAll
              onCheck={this.onCheck}
              checkedKeys={checkedKeys}
              treeData={treeData}
            />
          </Form>
        </Modal>
      </Card>
    )
  }
}